from flask import render_template, request, jsonify
from . import ingredient_bp
from ..utils.stats import record_api_call
import requests
import base64
import json

# 百度云API配置
API_KEY = 'ZWsM40uWHibmA6hu4nct354X'
SECRET_KEY = 'dmJoOzQLISTBLooGcnxNsYaetBpfove0'

def get_access_token():
    """获取百度AI平台的access_token"""
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    response = requests.post(url, params=params)
    if response:
        return response.json().get("access_token")
    return None

@ingredient_bp.route('/')
def index():
    """果蔬识别页面"""
    return render_template('modules/ingredient_recognition.html')

@ingredient_bp.route('/recognize', methods=['POST'])
def recognize():
    """处理果蔬识别请求"""
    try:
        # 检查是否有文件上传
        if 'image' not in request.files:
            return jsonify({'error': '没有上传图片'}), 400
        
        file = request.files['image']
        if file.filename == '':
            return jsonify({'error': '没有选择图片'}), 400
        
        # 读取图片数据
        image_data = file.read()
        image_base64 = base64.b64encode(image_data).decode('utf-8')
        
        # 获取access token
        access_token = get_access_token()
        if not access_token:
            return jsonify({'error': '获取access token失败'}), 500
        
        # 调用百度果蔬识别API
        url = f"https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient?access_token={access_token}"
        
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        
        data = {
            'image': image_base64,
            'top_num': 5  # 返回top5的结果
        }
        
        response = requests.post(url, headers=headers, data=data)
        
        if response.status_code == 200:
            result = response.json()
            
            # 记录API调用
            record_api_call('ingredient_recognition')
            
            # 处理识别结果
            if 'result' in result:
                return jsonify({
                    'results': [
                        {
                            'name': item['name'],
                            'score': item['score']
                        }
                        for item in result['result']
                    ]
                })
            else:
                return jsonify({'results': []})
        else:
            return jsonify({'error': '识别服务异常'}), 500
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500 